package com.dhh.sky.service;

import java.util.List;
import org.json.JSONObject;
import android.content.Intent;
import android.util.Log;
import com.dhh.sky.R;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.model.Operation;
import com.dhh.sky.model.SkyDriveObject;
import com.dhh.sky.util.Constant;
import com.dhh.sky.util.JsonKeys;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveOperationListener;

public class NewOperationService extends BasicOperationService{

	public NewOperationService() {
		super(Constant.SERVICE_NAME_NEW_FOLDER);
	}

	@Override
	protected void doOperation(Intent intent) {
		message = this.getString(R.string.msg_error_create_folder);
		create();		
		
	}
	
	private void create(){
		try{		
			if(next()){  
				path = op.getPath();
				JSONObject body = new JSONObject(op.getMeta());
				createFolder(op.getPath(),body);
				oManager.removeOperation(op.getPath(), Operation.OP_CREATE_FOLDER); 
			}
		}catch(Exception e){
			Log.e(Constant.TAG, e.getMessage(), e);
		}
	}
	
	private boolean next(){
		boolean flag = false;
		List<Operation> ops = oManager.getOperationReady(Operation.OP_CREATE_FOLDER);
		if(ops.size()>0){
			flag = true;
			op = ops.get(0);
			Log.d(Constant.TAG, "create folder next(): "+op.getPath());
		}
		return flag;
	}
	
	private boolean createFolder(String id,JSONObject body){
		boolean flag = false;
        
        try {
        	mClient = ((SDAApplication) getApplication()).getConnectClient();
        	mClient.postAsync(id, body, new LiveOperationListener(){
				@Override
				public void onComplete(LiveOperation operation) {
					JSONObject result = operation.getResult();
					boolean succ = !result.has(JsonKeys.ERROR);
					if(succ){
						SkyDriveObject folder = SkyDriveObject.create(result);
						folder.setParent(path);
						fManager.addFile(folder);
					}
					
					response(succ,message,path);					
					create();
				}

				@Override
				public void onError(LiveOperationException exception,LiveOperation operation) {
					response(false,message,path);
					create();
				}
			});
		} catch (Exception e) {
			Log.e(Constant.TAG, e.getMessage(), e);
		}
        
        return flag;
        
	}

}
